import React, {Component} from 'react';
import {Icon, Layout, Menu, Row, Col, Badge, Modal} from 'antd';
import {Route, Switch} from 'react-router-dom';
import logo from '../image/u219.png';
import storeInfo from './storeInfo';
import orderManage from './orderManage';
import goodManage from './goodManage';
import goodTypeManage from './goodTypeManage';
import goodAdd from './goodAdd';
import tableManage from './tableManage';

import news from '../image/u253.png';
import exit from '../image/exit.png';

import app from '../AppMethod';
import {menu} from "../value";
import {config} from "../config";
import '../css/index.css';

import {Consumer} from "../store";//引入上下文

const {Header, Sider, Content} = Layout;
const SubMenu = Menu.SubMenu;
const confirm = Modal.confirm;

const loop = (menu, data) => {
    let menuList = [];
    data.map((item, index) => {
        if (menu.menu_id === item.menu_parentid) {
            menuList.push(item);
            menu.subList = menuList;
            loop(item, data);
        } else {
            menuList = [];
        }
    })
};

class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            collapsed: false,
            key: '0',
            mode: "inline",
            menuListData: [
                {
                    menu_icon: "team",
                    menu_id: "c17f7d49df61ed4f8ada075d15e8adb4",
                    menu_name: "店铺基本信息",
                    menu_path: "/storeInfo"
                },
                {
                    menu_icon: "team",
                    menu_id: "c17f7d49df61ed4f8ada075d15e8adb5",
                    menu_name: "订单管理",
                    menu_path: "/orderManage/orderStatistic"
                },
                {
                    menu_icon: "team",
                    menu_id: "c17f7d49df61ed4f8ada075d15e8adb6",
                    menu_name: "商品管理",
                    menu_path: "/goodManage"
                },
                {
                    menu_icon: "team",
                    menu_id: "c17f7d49df61ed4f8ada075d15e8adb7",
                    menu_name: "分类管理",
                    menu_path: "/goodTypeManage"
                },
                {
                    menu_icon: "team",
                    menu_id: "c17f7d49df61ed4f8ada075d15e8adb8",
                    menu_name: "添加商品",
                    menu_path: "/goodAdd"
                },
                {
                    menu_icon: "team",
                    menu_id: "c17f7d49df61ed4f8ada075d15e8adb9",
                    menu_name: "餐桌管理",
                    menu_path: "/tableManage"
                }
            ],
            routeList: [
                {path: '/storeInfo', component: storeInfo},
                {path: '/orderManage', component: orderManage},
                {path: '/goodManage', component: goodManage},
                {path: '/goodTypeManage', component: goodTypeManage},
                {path: '/goodAdd', component: goodAdd},
                {path: '/tableManage', component: tableManage},
            ],
            current: '1',
            username: 'momo.zxy',
            openKeys: [],
            rootSubmenuKeys: [],
        }
    };

    toggle = () => {
        this.setState({
            collapsed: !this.state.collapsed
        })
    };

    render() {
        const platForm = '/index';
        return (
            <Layout style={{height: '100%'}}>
                <Sider
                    trigger={null}
                    collapsible={true}
                    collapsed={this.state.collapsed}
                    width="220"
                    height="100%"
                    style={{boxShadow: '2px 0 6px rgba(0,21,41,.35)'}}
                >
                    <Row className="logo" style={{
                        verticalAlign: 'middle',
                        height: '64px',
                        lineHeight: '64px',
                        backgroundColor: '#00284d'
                    }}>
                        <img alt="null" src={logo} style={{width: '150px', marginLeft: '20px'}}/>
                    </Row>
                    <Menu theme="dark" mode="inline" onClick={(e) => this.handleClick(e)}
                          selectedKeys={[this.state.current]} onOpenChange={this.handleOnOpenChange}
                          openKeys={this.state.openKeys}>
                        {
                            this.state.menuListData.map((item, index) => {
                                return (
                                    <Menu.Item key={platForm + item.menu_path} rowkey={index}>
                                            <span>
                                                <Icon type={item.menu_icon}/>
                                                <span>{item.menu_name}</span>
                                            </span>
                                    </Menu.Item>
                                )
                            })
                        }
                    </Menu>
                </Sider>
                <Layout style={{height: '100%', zIndex: 99}}>
                    <Header className="headerContainer">
                        <Icon
                            className="trigger headerContainerIcon"
                            type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'}
                            onClick={this.toggle}
                        />

                        <Row className="headerContainerRight">
                            <div className="headerContainerRightContainer">
                                <span className="headerContainerUserInfo">
                                    欢迎您，{this.state.username}
                                </span>
                                <span style={{marginLeft: '15px'}} onClick={() => this.handleExit()}>
                                <img alt="exit"
                                     title="退出"
                                     src={exit}
                                     style={{
                                         width: '24px',
                                         height: '24px',
                                         cursor: 'pointer'
                                     }}/>
                            </span>
                            </div>
                        </Row>
                    </Header>
                    <Content className="contentStyle">
                        <Switch>
                            {
                                this.state.routeList.map((item, index) => {
                                    return (
                                        <Route key={index} path={platForm + item.path} component={item.component}/>
                                    )
                                })
                            }
                        </Switch>
                    </Content>
                </Layout>
            </Layout>
        )
    };

    componentDidMount() {
        let selectKey = app.getData('selectKey');
        console.log(selectKey);
        let openKeys = app.getData('openKeys');
        if (selectKey) {
            this.setState({current: selectKey});
        }
        if (openKeys && openKeys.length > 0) {
            this.setState({openKeys: openKeys});
        }
        window._this = this;
        //this.handleSearchMenuList();
    };

    /**
     * 处理菜单栏点击跳转页面
     * @param e
     */
    handleClick = (e) => {
        this.setState({
            current: e.key,
        });
        app.setData('selectKey', e.key);
        this.props.history.push(e.key);
    };

    /**
     * 获取菜单栏列表
     */
    handleSearchMenuList() {
        let token = app.getToken();
        let firstMenu = [];
        if (!token) {
            app.alert("您还未登录", "error", 3);
            this.props.history.push("/login");
            return;
        } else {
            let username = app.getData("username");
            this.setState({username});
            let menuList = app.getData("menu");
            if (menuList && menuList.length > 0) {
                menuList.map((item) => {
                    if (item.menu_level === 1) {
                        firstMenu.push(item);
                    }
                });
                firstMenu.map((item) => {
                    loop(item, menuList);
                });
                console.log(firstMenu);
                this.setState({menuListData: firstMenu});
            } else {
                this.setState({menuListData: []});
            }
        }
        this.handleGetMenuKey(firstMenu);
    };

    /**
     * 获取菜单key
     */
    handleGetMenuKey(menuListData) {
        let keyData = [];
        menuListData.map((item, index) => {
            if (item.subList) {
                index = index.toString();
                keyData.push(index);
            }
        });
        console.log(keyData);
        this.setState({rootSubmenuKeys: keyData});
    }

    /**
     * 处理菜单栏展开/收起操作
     * @param openKeys
     */
    handleOnOpenChange = (openKeys) => {
        let latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
        if (this.state.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
            this.setState({openKeys});
            app.setData('openKeys', JSON.stringify(openKeys));
        } else {
            let openKeys = latestOpenKey ? [latestOpenKey] : [];
            this.setState({
                openKeys: openKeys,
            });
            app.setData('openKeys', JSON.stringify(openKeys));
        }
    };

    /**
     * 处理退出系统事件
     */
    handleExit() {
        const _this = this;
        confirm({
            title: '',
            content: '您确认退出吗？',
            onOk() {
                app.removeToken();
                app.removeDate("menu");
                app.removeDate("username");
                _this.props.history.push('/login');
            },
            onCancel() {

            }
        })
    }
}

export default prop => (
    <Consumer>
        {
            props => (
                <Index {...prop} {...props}/>
            )
        }
    </Consumer>
);